//
//  EeFilterItem.swift
//  soapp_Example
//
//  Created by zhu xietong on 2018/5/6.
//  Copyright © 2018年 CocoaPods. All rights reserved.
//

import Foundation
import Eelay
import JoLoading

open class EeButton: UIButton {
    open override func layoutSubviews() {
        super.layoutSubviews()
        
        
        
        switch self.ui.imgPosition {
        case .right:
            let interval:CGFloat = 8.0
            let font = titleLabel?.font ?? UIFont.systemFont(ofSize: 12)
            let titleSize = NSString(string: self.titleLabel?.text ?? "").size(withAttributes: [NSAttributedString.Key.font:font])
            let imageSize = self.image(for: .normal)?.size ?? .zero
            
            //            let oss = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
            self.imageEdgeInsets = UIEdgeInsets(top: 0,left: titleSize.width + interval, bottom: 0, right: -(titleSize.width + interval));
            self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize.width + interval), bottom: 0, right: imageSize.width + interval);
            
//            var imageRect = imageView?.frame ?? .zero
//            let size = imageView?.frame.size ?? .zero
//
//            imageRect.size = size
//            imageRect.origin.x = (self.frame.size.width - size.width) ;
//            imageRect.origin.y = (self.frame.size.height  - size.width)/2.0
//            var titleRect = self.titleLabel?.frame ?? .zero
//            titleRect.origin.x = (self.frame.size.width - imageRect.size.width - titleRect.size.width);
//            titleRect.origin.y = (self.frame.size.height - titleRect.size.height)/2.0;
//            self.imageView?.frame = imageRect;
//            self.titleLabel?.frame = titleRect;
        default:
            break
        }
        
    }
}

extension EeFilterMenu{
    public enum Notice:String,NotifyType {
        case itemToggle = "itemToggle"
        
        public var name: Notification.Name{
            return "EeFilterMenu.\(Notice.self).\(self.rawValue)".notice_name
        }
    }
}

public enum FilterType{
    case order
    case options
}

public protocol FilterItemSupport {
    var itemWidth:CGFloat{get set}
    var button:EeButton{get set}
    var buttonAction:(UIButton)->Void{get set}
    var type:FilterType{get set}
    
    var owner:EeFilterMenu?{get set}
    
    func updateDisplay()
    
    var filterKey:String{get set}
    var filterValues:[String:Any]?{get}
    var align:NSTextAlignment{set get}


    
    
}

open class FilterItem:NSObject,FilterItemSupport{
    
    
    public var align = NSTextAlignment.center
    

    
    
    public var filterKey: String = ""
    
    open var filterValues: [String : Any]?{
        get{
            return nil
        }
    }
    
    open func updateDisplay() {
        
    }
    
    public var __notice: EasyNotification = EasyNotification()
    public var button: EeButton = EeButton()
    public weak var owner:EeFilterMenu? = nil
    public var itemWidth: CGFloat = 50
    public var pramas:[String:Any] = [:]
    public var type: FilterType = .order
    
    public var buttonAction: (UIButton) -> Void = {_ in}
    
    
    public override init() {
        super.init()
        
        
        weak var wself = self
        
        __notice.observer(EeFilterMenu.Notice.itemToggle) { (notify_type, notification) in
            guard let item = notification.object as? FilterItem, let ws = wself else{
                return
            }
            if ws === item{
                return
            }
            
            
            guard let ws_menu = ws.owner,let item_menu = item.owner else{
                return
            }
            
            if ws_menu === item_menu{
                if ws.type == item.type{
                    ws.unSelect()
                }
            }
        }
        button.contentEdgeInsets = [12,14]
        button.addTarget(self, action: #selector(__buttonPressed(sender:)), for: .touchUpInside)
    }
    
    open func unSelect() {
        button.isSelected = false
        buttonAction(button)
    }
    
    open func doSelect() {
        
    }
    
    
    
    open func buttonPressed(sender:UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected
        {
            doSelect()
            __post(notify: EeFilterMenu.Notice.itemToggle, object: self, userInfo: nil)
        }
        else{
            unSelect()
        }
    }
    
    
    @objc open func __buttonPressed(sender:UIButton) {
        
        buttonPressed(sender: sender)
        buttonAction(sender)

    }
    
}

public class FilterOrder:FilterItem{
    public var asc:(name:String,key:String,value:String,icon:UIImage?) = ("升","price","asc",nil)
    public var desc:(name:String,key:String,value:String,icon:UIImage?)? = nil
    
    public var selectedColor = UIColor(shex: "#555")
    public var normalColor = UIColor(shex: "#888")
    
    public override init() {
        super.init()
        self.filterKey = "order"
        button.contentEdgeInsets = [40,40]
    }
    
    public override var filterValues: [String : Any]?{
        get{
            if let _desc = desc
            {
                if isAsc
                {
                    return ["title":asc.name,"by":asc.value,"orderKey":asc.key,"name":filterKey]
                }
                else{
                    return ["title":_desc.name,"by":_desc.value,"orderKey":_desc.key,"name":filterKey]
                }
            }
            else{
                return ["title":asc.name,"by":asc.value,"orderKey":asc.key,"name":filterKey]
            }
        }
    }
    
    public override func unSelect() {
        button.isSelected = false
        updateDisplay()
    }
    
    var index:Int = 0
    @objc override public func buttonPressed(sender:UIButton) {
        guard let menu = self.owner else{return}
        menu.control.close()

        if button.isSelected{
            index = index + 1
        }
        button.isSelected = true
        updateDisplay()
        
        __post(notify: EeFilterMenu.Notice.itemToggle, object: self, userInfo: nil)
        let values = filterValues ?? [String:Any]()
        menu.updateFilterValues(values: values)
        buttonAction(sender)
    }
    
    var isAsc:Bool{
        if index % 2 == 0{
            return true
        }
        return false
                
            
    }
    
    override public func updateDisplay() {
        if let _desc = desc
        {
            if !isAsc{
                button.setImage(_desc.icon, for: .normal)
                button.setImage(_desc.icon, for: .selected)

                button.setTitle(_desc.name, for: .selected)
                button.setTitle(_desc.name, for: .normal)
            }
            else{
                button.setImage(asc.icon, for: .normal)
                button.setImage(asc.icon, for: .selected)

                button.setTitle(asc.name, for: .selected)
                button.setTitle(asc.name, for: .normal)
            }
        }
        else{
            button.setImage(asc.icon, for: .normal)
            button.setImage(asc.icon, for: .selected)
            
            button.setTitle(asc.name, for: .selected)
            button.setTitle(asc.name, for: .normal)
        }
        
    }
    
    
}


public enum EeFilterSelector {
    case dropView(FilterDropSelector)
    case push(FilterOptionsSelectorController)
    case present(FilterOptionsSelectorController,anmimated:Bool)
    case action(open:()->Void)
    case none
}


open class FilterOption:FilterItem{
    


    public override init() {
        super.init()
      
        self.type = .options
        
    }
    
    public var isSelected:Bool=false{
        didSet{
            button.isSelected = isSelected
            buttonAction(button)

        }
    }
    
    @objc override open func buttonPressed(sender:UIButton) {
        if button.isSelected{
            button.isSelected = false
            hidenSelector()
        }
        else{
            doSelect()
            __post(notify: EeFilterMenu.Notice.itemToggle, object: self, userInfo: nil)
        }
        buttonAction(sender)
    }
    
    open override func doSelect() {
        guard let menu = self.owner else{return}
        menu.control.open(item: self)
        switch filterSelector {
        case .dropView(let selector):
            selector.didShow()
        case .push(let ctr):
            button.isSelected = false

            if let nav = owner?.controller as? UINavigationController
            {
                nav.pushViewController(ctr, animated: true)
            }
            else{
                owner?.controller?.navigationController?.pushViewController(ctr, animated: true)
            }
        case .present(let ctr,let animated):
            owner?.controller?.present(ctr, animated: animated, completion: nil)          
        default:
            break
        }
    }
    
    open func hidenSelector() {
        guard let menu = self.owner else{return}
        menu.control.close()
        switch filterSelector {
        case .dropView(let selector):
            selector.didHidden()
        case .present(_, anmimated: _),.push(_):
            break
        default:
            break
        }
    }
    
    
    public var filterSelector = EeFilterSelector.none{
        didSet{
            switch filterSelector {
            case .push(let ctr):
                ctr.owner = self
            case .present(let ctr,_):
                ctr.owner = self
            case .dropView(let selector):
                selector.owner = self
            default:
                break
            }
        }
    }
    
    
    var values:[String:Any]? = nil
    
    open override var filterValues: [String : Any]?{
        get{
            return values
        }
    }
}

open class FilterOptionsSelectorController:TypeInitController{
    public weak var owner:FilterOption? = nil
    open func confirm(values:[String:Any]){
        self.owner?.values = values
        self.owner?.owner?.updateFilterValues(values: values)
        self.owner?.hidenSelector()
    }
    
    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.owner?.hidenSelector()
    }

}

open class FilterDropSelector: JoView,LoadingPresenter{
    public var loadingPresenterInset: UIEdgeInsets{
        get{
            return .zero
        }
    }
    
    public var contentView = UIView()
    
    public var flexBoundsFix:CGFloat = 38//下拉弹跳漏出修改
    
    open var contentHeight:CGFloat{
        return 200.co
    }
   
    open override func willLayoutRules() {
        jo_contentView.eelay = [
            [contentView,[ee.T,flexBoundsFix],[ee.L.B.R]]
        ]
        backgroundColor = .clear
        jo_contentView.backgroundColor = ._background
    }
    
    
    open override var intrinsicContentSize: CGSize
        {
        get{
            return CGSize(width: Swidth, height: (contentHeight + flexBoundsFix))
        }
    }
    
    open func confirm(values:[String:Any]){
        self.owner?.values = values
        self.owner?.owner?.updateFilterValues(values: values)
        self.owner?.hidenSelector()
    }
    
    public weak var owner:FilterOption? = nil
    open func didShow(){}
    open func didHidden(){}

}
